package com.ifp.weixin.biz.core.impl;

import com.ifp.weixin.biz.core.BusLineSearch;
import com.ifp.weixin.biz.core.CoreService;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.swing.text.AbstractDocument.Content;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.ifp.weixin.biz.core.CoreService;
import com.ifp.weixin.constant.Constant;
import com.ifp.weixin.MessageMng.Message.bus.BusLine;
import com.ifp.weixin.MessageMng.Message.bus.BusSearchInput;
import com.ifp.weixin.MessageMng.Message.resp.Article;
import com.ifp.weixin.MessageMng.Message.resp.RespNewsMessage;
import com.ifp.weixin.MessageMng.Message.resp.RespArticleInfoDefine;
import com.ifp.weixin.MessageMng.Message.resp.RespMsgInfoDefine;
import com.ifp.weixin.MessageMng.Message.resp.RespTextMessage;
import com.ifp.weixin.MessageMng.Message.req.LinkMessage;
import com.ifp.weixin.MessageMng.Message.req.ReqNormalEventMessage;
import com.ifp.weixin.MessageMng.Message.req.ReqBaseMessage;
import com.ifp.weixin.MessageMng.Message.req.ReqLocationMessage;
import com.ifp.weixin.MessageMng.Message.req.ReqTextMessage;
import com.ifp.weixin.MessageMng.Message.req.ReqVideoMessage;
import com.ifp.weixin.MessageMng.Message.req.VoiceMessage;
import com.ifp.weixin.MessageMng.Service.LocationMessageService;
import com.ifp.weixin.MessageMng.Service.RespArticleInfoDefineService;
import com.ifp.weixin.MessageMng.Service.RespReqdealRelaService;
import com.ifp.weixin.util.MessageUtil;
import com.ifp.weixin.util.RequestParse;
import com.sun.xml.internal.bind.v2.runtime.Name;

@Service("coreService")
public class CoreServiceImpl implements CoreService {

	public static Logger log = Logger.getLogger(CoreServiceImpl.class);
	@Resource(name="requestParseService")
	public RequestParse requestParse;
	
	@Resource(name="busLineSearchService")
	public BusLineSearch busLineSearchService;
	
	@Resource(name="locationMessageService")
	public LocationMessageService locationMessageService;	
	
	@Resource(name="respArticleInfoDefineService")
	public RespArticleInfoDefineService respArticleInfoDefineService;	
	
	@Resource(name="respReqdealRelaService")
	public RespReqdealRelaService respReqdealRelaService;	
	
	
		public String processRequest(HttpServletRequest request) {
			System.out.println("into  processRequest............. " );
			String respMessage = null;
			ReqBaseMessage reqBaseMessage = null;
			BusSearchInput busSearchInput = new BusSearchInput();
			try {
				// xml请求解析
				Map<String, String> requestMap = MessageUtil.parseXml(request);

				// 消息类型
				String msgType = requestMap.get("MsgType");
				reqBaseMessage = this.makeReqMessage(requestMap);
				// 文本消息
				if ( reqBaseMessage.getMsgType().equals(Constant.REQ_MESSAGE_TYPE_TEXT )) {
					
					respMessage = processTextReq( reqBaseMessage );
					// 接收用户发送的文本消息内容
				
				} else if ( reqBaseMessage.getMsgType().equals(Constant.REQ_MESSAGE_TYPE_LOCATION )) {
					
					respMessage = processLocationReq(reqBaseMessage);
					// 接收用户发送的位置消息				
				} else if ( reqBaseMessage.getMsgType().equals(Constant.REQ_MESSAGE_TYPE_EVENT )) {
					
					respMessage = processEventReq( reqBaseMessage );
					// 接收用户发送的事件消息				
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return respMessage;
		}

		private ReqBaseMessage makeEventReq(Map<String, String> requestMap) {
			// TODO Auto-generated method stub
			return null;
		}

		private String processLocationReq( ReqBaseMessage reqBaseMessage) {
			// TODO 自动生成方法存根
			// TODO 自动生成方法存根
			String respMessage = null;
//			 发送方帐号（open_id）
		
			ReqLocationMessage reqLocationMessage =(  ReqLocationMessage ) reqBaseMessage;
			
			RespTextMessage respTextMessage = new RespTextMessage();
			respTextMessage.setCreateTime( new Date().getTime() );
			respTextMessage.setMsgType(Constant.RESP_MESSAGE_TYPE_TEXT);
			
			respTextMessage.setToUserName( reqLocationMessage.getFromUserName() );
			respTextMessage.setFromUserName( reqLocationMessage.getToUserName() );
			respTextMessage.setCreateTime(new Date().getTime());
			
		
			reqLocationMessage.setInsert_Time( new Date() );
			reqLocationMessage.setUpdate_Time(new Date() ) ;
		
			try {
				System.out.println("into locationMessageService.add");
				locationMessageService.add(reqLocationMessage);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.println("77777777777777");
			StringBuffer sBuffer = new StringBuffer();
			sBuffer.append("您的位置是："+"\n");
			sBuffer.append(reqLocationMessage.getLabel());
			System.out.println("sBuffer = " + sBuffer.toString() );
			respTextMessage.setContent(sBuffer.toString());
			respMessage = MessageUtil.textMessageToXml(respTextMessage);
			
			return respMessage;
		}
		
		private String processEventReq( ReqBaseMessage reqBaseMessage) {
			// TODO 自动生成方法存根
			String respMessage = null;
			ReqNormalEventMessage  reqNormalEventMessage= (ReqNormalEventMessage )reqBaseMessage;
			RespMsgInfoDefine respMsgInfoDefine = null;
			
			respMsgInfoDefine = respReqdealRelaService.getRelasByEventAndKey( reqNormalEventMessage.getEvent(),
																			reqNormalEventMessage.getEventKey()
			);
			
			
			//如果需要发文本消息
			if ( respMsgInfoDefine.getMsgType().equals( Constant.REQ_MESSAGE_TYPE_TEXT )) {
				
				RespTextMessage resptextMessage = new RespTextMessage();
				resptextMessage.setToUserName( reqNormalEventMessage.getFromUserName() );
				resptextMessage.setFromUserName( reqNormalEventMessage.getToUserName() );
				resptextMessage.setCreateTime(new Date().getTime());
				resptextMessage.setMsgType(respMsgInfoDefine.getMsgType());
				//resptextMessage.setContent(respMsgInfoDefine.getContent());
				resptextMessage.setContent(respMsgInfoDefine.getContent().replace("\\n",System.getProperty("line.separator") ) );
				respMessage = MessageUtil.textMessageToXml( resptextMessage );
				
			} else	if ( respMsgInfoDefine.getMsgType().equals( Constant.RESP_MESSAGE_TYPE_NEWS )) {
				//如果需要发图文消息
				RespNewsMessage respNewsMessage = new RespNewsMessage();
				respNewsMessage.setToUserName( reqBaseMessage.getFromUserName() );
				respNewsMessage.setFromUserName( reqBaseMessage.getToUserName() );
				respNewsMessage.setCreateTime(new Date().getTime());
				respNewsMessage.setMsgType(respMsgInfoDefine.getMsgType());
				
				List<Article> artcList = new ArrayList<Article>();
				
				List<RespArticleInfoDefine> articleList = respMsgInfoDefine.getArticles();
				

				
				if ( articleList != null && articleList.size()>0 ) {
					
					
					for (int i = 0; i < articleList.size(); i++) {
						
						RespArticleInfoDefine respArticleInfoDefine ;
						
						respArticleInfoDefine = articleList.get(i);


						if ( null != respArticleInfoDefine && null != respArticleInfoDefine.getTitle()  && ! ( "".equals( respArticleInfoDefine.getTitle() ) ) ) {
							
							Article article = new Article();
							
							article.setTitle( respArticleInfoDefine.getTitle()  );
							article.setDescription ( respArticleInfoDefine.getDescription() );
							article.setUrl ( respArticleInfoDefine.getUrl() );
							article.setPicUrl ( respArticleInfoDefine.getPicUrl() );
							artcList.add( article );
						}
					}
				}
				
				respNewsMessage.setArticleCount(  artcList.size());
				respNewsMessage.setArticles( artcList );
				respMessage = MessageUtil.newsMessageToXml(respNewsMessage);
			} 
			return respMessage;
		}

		private String processTextReq( ReqBaseMessage reqBaseMessage ) {
			// TODO 自动生成方法存根
			String respMessage = null;
			ReqTextMessage  reqTextMessage= (ReqTextMessage )reqBaseMessage;
			RespMsgInfoDefine respMsgInfoDefine = null;
			
			
			BusSearchInput busSearchInput = new BusSearchInput();

			if ( requestParse.parseBusLineSearch( reqTextMessage.getContent() ,  busSearchInput) > 0 ) {
					//公交查询
				String searchresp =null;
				RespTextMessage resptextMessage = new RespTextMessage();
				resptextMessage.setToUserName( reqTextMessage.getFromUserName() );
				resptextMessage.setFromUserName( reqTextMessage.getToUserName() );
				resptextMessage.setCreateTime(new Date().getTime());
				resptextMessage.setMsgType(Constant.REQ_MESSAGE_TYPE_TEXT);
				searchresp = busLineSearchService.SearchBusLineStr(busSearchInput.getCity(),busSearchInput.getQ(),busSearchInput.getWith_xys());
				
				resptextMessage.setContent(searchresp);
				respMessage = MessageUtil.textMessageToXml(resptextMessage);					
			} 	else {		
			
				respMsgInfoDefine = respReqdealRelaService.getMsgByFeatureKey( reqTextMessage.getContent());
				//如果需要发文本消息
				if ( respMsgInfoDefine.getMsgType().equals( Constant.RESP_MESSAGE_TYPE_TEXT )) {
					StringBuffer sBuffer = new StringBuffer();
					RespTextMessage resptextMessage = new RespTextMessage();
					resptextMessage.setToUserName( reqTextMessage.getFromUserName() );
					resptextMessage.setFromUserName( reqTextMessage.getToUserName() );
					resptextMessage.setCreateTime(new Date().getTime());
					resptextMessage.setMsgType(respMsgInfoDefine.getMsgType());
					
					resptextMessage.setContent(respMsgInfoDefine.getContent().replace("\\n",System.getProperty("line.separator") ) );
					
					respMessage = MessageUtil.textMessageToXml( resptextMessage );
					
				} else	if ( respMsgInfoDefine.getMsgType().equals( Constant.RESP_MESSAGE_TYPE_NEWS )) {
					//如果需要发图文消息
					RespNewsMessage respNewsMessage = new RespNewsMessage();
					respNewsMessage.setToUserName( reqBaseMessage.getFromUserName() );
					respNewsMessage.setFromUserName( reqBaseMessage.getToUserName() );
					respNewsMessage.setCreateTime(new Date().getTime());
					respNewsMessage.setMsgType(respMsgInfoDefine.getMsgType());
					
					List<Article> artcList = new ArrayList<Article>();
					
					List<RespArticleInfoDefine> articleList = respMsgInfoDefine.getArticles();
					
					if ( articleList != null && articleList.size()>0 ) {
						
						for (int i = 0; i < articleList.size(); i++) {
							
							RespArticleInfoDefine respArticleInfoDefine ;
							
							respArticleInfoDefine = articleList.get(i);
	
							if ( null != respArticleInfoDefine && null != respArticleInfoDefine.getTitle()  && ! ( "".equals( respArticleInfoDefine.getTitle() ) ) ) {
								
								Article article = new Article();
								
								article.setTitle( respArticleInfoDefine.getTitle()  );
								article.setDescription ( respArticleInfoDefine.getDescription() );
								article.setUrl ( respArticleInfoDefine.getUrl() );
								article.setPicUrl ( respArticleInfoDefine.getPicUrl() );
								artcList.add( article );
							}
						}
					}
					
					respNewsMessage.setArticleCount(  artcList.size());
					respNewsMessage.setArticles( artcList );
					respMessage = MessageUtil.newsMessageToXml(respNewsMessage);
					
				} else {
		 
					RespTextMessage resptextMessage = new RespTextMessage();
					resptextMessage.setToUserName( reqTextMessage.getFromUserName() );
					resptextMessage.setFromUserName( reqTextMessage.getToUserName() );
					resptextMessage.setCreateTime(new Date().getTime());
					resptextMessage.setMsgType(Constant.REQ_MESSAGE_TYPE_TEXT);
					
					StringBuffer sBuffer = new StringBuffer();
					sBuffer.append(Constant.USER_NORMAL_HELP);
					
					resptextMessage.setContent(sBuffer.toString());
					respMessage = MessageUtil.textMessageToXml(resptextMessage);
				
					 
				}
			}
			return respMessage;
	
		}

		public void  haha() {
			System.out.println("hahahahaha............. " );
			
		}
		
		public ReqBaseMessage makeReqMessage(Map<String, String> requestMap) {
			String fromUserName = requestMap.get("FromUserName");
			String msgType = requestMap.get("MsgType");
			String toUserName = requestMap.get("ToUserName");
			ReqBaseMessage  baseMessage =null;
			// 文本消息
			if ( msgType.equals( Constant.REQ_MESSAGE_TYPE_TEXT )) {
				  baseMessage=  makeTextReq(requestMap);
				// 接收用户发送的文本消息内容
			
			} else if ( msgType.equals( Constant.REQ_MESSAGE_TYPE_LOCATION )) {
				 baseMessage = makeLocationReq(requestMap);
						
			} else if ( msgType.equals(Constant.REQ_MESSAGE_TYPE_IMAGE )) {
				 baseMessage = makeLocationReq(requestMap);
						
			} else if ( msgType.equals(Constant.REQ_MESSAGE_TYPE_VOICE )) {
				 baseMessage = makeVoiceReq(requestMap);
						
			} else if ( msgType.equals(Constant.REQ_MESSAGE_TYPE_LINK )) {
				 baseMessage = makeLinkReq(requestMap);
						
			} else if ( msgType.equals(Constant.REQ_MESSAGE_TYPE_VIEDO )) {
				 baseMessage = makeViedoReq(requestMap);
						
			} else if ( msgType.equals(Constant.REQ_MESSAGE_TYPE_EVENT ) ) {
				 
				String eventType = requestMap.get("Event");
				if ( eventType.equals(Constant.TYPE_EVENT_CLICK ) )  {
					
					baseMessage = makeEventClickReq(requestMap);
					
				} else if ( eventType.equals(Constant.TYPE_EVENT_LOCATION ) ) {
					
					baseMessage = makeEventLocationReq(requestMap);
					
				} else if (  eventType.equals(Constant.TYPE_EVENT_SUBSCRIBE ) ) {
					
					baseMessage = makeEventSubscribeReq(requestMap);
					
				} else if ( eventType.equals(Constant.TYPE_EVENT_UNSUBSCRIBE ) ) {
					
					baseMessage = makeEventUnSubscribeReq(requestMap);
				}
				  else if ( eventType.equals(Constant.TYPE_EVENT_VIEW )) {
					  
					baseMessage = makeEventViewReq(requestMap);
				}  
				
							
			} 					
			return baseMessage;
		}

		private ReqBaseMessage makeTextReq(Map<String, String> requestMap) {
			// TODO 自动生成方法存根
			ReqTextMessage reqTextMessage = new ReqTextMessage();
			reqTextMessage.setFromUserName( requestMap.get("FromUserName") );
			reqTextMessage.setToUserName( requestMap.get("ToUserName") );
			reqTextMessage.setCreateTime( Long.parseLong( requestMap.get("CreateTime")  ) );
			reqTextMessage.setMsgType( requestMap.get("MsgType") );
			reqTextMessage.setMsgId( Long.parseLong( requestMap.get("MsgId") ) );
			
			reqTextMessage.setContent(  requestMap.get("Content") );
			
			return reqTextMessage;
		}



		private ReqBaseMessage makeEventViewReq(Map<String, String> requestMap) {
			// TODO 自动生成方法存根
			
			
			return null;
		}

		private ReqBaseMessage makeEventUnSubscribeReq(Map<String, String> requestMap) {
			// TODO 自动生成方法存根
			ReqNormalEventMessage normalEventMessage = new ReqNormalEventMessage();
			normalEventMessage.setFromUserName( requestMap.get("FromUserName") );
			normalEventMessage.setToUserName( requestMap.get("ToUserName") );
			normalEventMessage.setCreateTime( Long.parseLong( requestMap.get("CreateTime")  ) );
			normalEventMessage.setMsgType( requestMap.get("MsgType") );
			//normalEventMessage.setMsgId( Long.parseLong( requestMap.get("MsgId") ) );
			
			normalEventMessage.setEvent(  requestMap.get("Event") );
			
			return normalEventMessage;			
			
		}

		private ReqBaseMessage makeEventSubscribeReq(Map<String, String> requestMap) {
			// TODO 自动生成方法存根
			ReqNormalEventMessage normalEventMessage = new ReqNormalEventMessage();
			normalEventMessage.setFromUserName( requestMap.get("FromUserName") );
			normalEventMessage.setToUserName( requestMap.get("ToUserName") );
			normalEventMessage.setCreateTime( Long.parseLong( requestMap.get("CreateTime")  ) );
			normalEventMessage.setMsgType( requestMap.get("MsgType") );
			//normalEventMessage.setMsgId( Long.parseLong( requestMap.get("MsgId") ) );
			
			normalEventMessage.setEvent(  requestMap.get("Event") );
			
			return normalEventMessage;	
		}

		private ReqBaseMessage makeEventLocationReq(Map<String, String> requestMap) {
			// TODO 自动生成方法存根
			ReqNormalEventMessage normalEventMessage = new ReqNormalEventMessage();
			normalEventMessage.setFromUserName( requestMap.get("FromUserName") );
			normalEventMessage.setToUserName( requestMap.get("ToUserName") );
			normalEventMessage.setCreateTime( Long.parseLong( requestMap.get("CreateTime")  ) );
			normalEventMessage.setMsgType( requestMap.get("MsgType") );
			normalEventMessage.setMsgId( Long.parseLong( requestMap.get("MsgId") ) );
			
			normalEventMessage.setLatitude( requestMap.get("Latitude") );
			normalEventMessage.setLongitude( requestMap.get("Longitude") );
			normalEventMessage.setPrecision( requestMap.get("Precision") );
			return normalEventMessage;	
		}

		private ReqBaseMessage makeEventClickReq(Map<String, String> requestMap) {
			// TODO 自动生成方法存根
			ReqNormalEventMessage normalEventMessage = new ReqNormalEventMessage();
			normalEventMessage.setFromUserName( requestMap.get("FromUserName") );
			normalEventMessage.setToUserName( requestMap.get("ToUserName") );
			normalEventMessage.setCreateTime( Long.parseLong( requestMap.get("CreateTime")  ) );
			normalEventMessage.setMsgType( requestMap.get("MsgType") );
			//normalEventMessage.setMsgId( Long.parseLong( requestMap.get("MsgId") ) );
			
			
			
			normalEventMessage.setEvent(  requestMap.get("Event") );
			normalEventMessage.setEventKey(  requestMap.get("EventKey") );

			return normalEventMessage;
		}

		private ReqBaseMessage makeViedoReq(Map<String, String> requestMap) {
			// TODO 自动生成方法存根
			ReqVideoMessage reqVideoMessage = new ReqVideoMessage();
			reqVideoMessage.setFromUserName( requestMap.get("FromUserName") );
			reqVideoMessage.setToUserName( requestMap.get("ToUserName") );
			reqVideoMessage.setCreateTime( Long.parseLong( requestMap.get("CreateTime")  ) );
			reqVideoMessage.setMsgType( requestMap.get("MsgType") );
			reqVideoMessage.setMsgId( Long.parseLong( requestMap.get("MsgId") ) );
			
			
			
			reqVideoMessage.setMediaId(requestMap.get("MediaId") );
			reqVideoMessage.setThumbMediaId(  requestMap.get("ThumbMediaId") );
	
			return reqVideoMessage;
		}

		private ReqBaseMessage makeLinkReq(Map<String, String> requestMap) {
			// TODO 自动生成方法存根
			LinkMessage  linkMessage = new LinkMessage();
			linkMessage.setFromUserName( requestMap.get("FromUserName") );
			linkMessage.setToUserName( requestMap.get("ToUserName") );
			linkMessage.setCreateTime( Long.parseLong( requestMap.get("CreateTime")  ) );
			linkMessage.setMsgType( requestMap.get("MsgType") );
			linkMessage.setMsgId( Long.parseLong( requestMap.get("MsgId") ) );
			
			linkMessage.setTitle( requestMap.get("Title") )  ;
			linkMessage.setDescription( requestMap.get("Description"));
			linkMessage.setUrl( requestMap.get("Url"));
			linkMessage.setUrl( requestMap.get("Url"));
			return linkMessage;
		}

		private ReqBaseMessage makeVoiceReq(Map<String, String> requestMap) {
			// TODO 自动生成方法存根
			VoiceMessage  voiceMessage = new VoiceMessage();
			voiceMessage.setFromUserName( requestMap.get("FromUserName") );
			voiceMessage.setToUserName( requestMap.get("ToUserName") );
			voiceMessage.setCreateTime( Long.parseLong( requestMap.get("CreateTime")  ) );
			voiceMessage.setMsgType( requestMap.get("MsgType") );
			voiceMessage.setMsgId( Long.parseLong( requestMap.get("MsgId") ) );
			
			voiceMessage.setMediaId(  requestMap.get("media_id") )  ;
			voiceMessage.setFormat( requestMap.get("Format"));
			return voiceMessage;
		}

		private ReqBaseMessage makeLocationReq(Map<String, String> requestMap) {
			// TODO 自动生成方法存根
			ReqLocationMessage locationMessage = new ReqLocationMessage();
			locationMessage.setFromUserName( requestMap.get("FromUserName") );
			locationMessage.setToUserName( requestMap.get("ToUserName") );
			locationMessage.setCreateTime( Long.parseLong( requestMap.get("CreateTime")  ) );
			locationMessage.setMsgType( requestMap.get("MsgType") );
			locationMessage.setMsgId( Long.parseLong( requestMap.get("MsgId") ) );
			
			locationMessage.setLocation_X(  requestMap.get("Location_X") );
			locationMessage.setLocation_Y(  requestMap.get("Location_Y") );
			locationMessage.setScale(  requestMap.get("Scale") );
			locationMessage.setLabel(  requestMap.get("Label") );
			return locationMessage;
		}


	
}
